<?
/*
	File Description : MySQL Interface class
*/

class DB {
	private $dbConnection;
	private $isConnected = false;
	private $DBConfig;

	protected $lastInsertId;
	protected $charset = "utf8";

	public $host = "";
	public $dbname = "";
	public $dbid = "";
	public $dbpassword = "";
	public $lastQuery = "";
	public $errno;
	public $err_msg;


	function __construct()	{

		switch(func_num_args())
		{
			case 0: // no args: use default
							return true;
			case 4:
							$this->host = func_get_arg(0);
							$this->dbname = func_get_arg(1);
							$this->dbid = func_get_arg(2);
							$this->dbpassword = func_get_arg(3);
							break;
			default:
							return false;

		}

		return $this->connect();
	}

	function initDB()	{
		$charset = $this->charset;

		$this->sqlQuery("set names $charset;");

		$this->sqlQuery("set autocommit = 0;");

	}

	function connect()	{
		if($this->isConnected) return true;

		$this->dbConnection = @mysql_connect($this->host,$this->dbid,$this->dbpassword);

		if($this->dbConnection)
		{
			$result = @mysql_select_db($this->dbname,$this->dbConnection);

			if($result) $this->initDB();

			$this->isConnected = true;

			return $result;
		}
		else return false;
	}

	function disconnect() {
		if(!$this->isConnected) return true;

		mysql_close($this->dbConnection);

		$this->isConnected = false;

		return true;
	}

	function writeLog($script) {
		$fname = $_SERVER[DOCUMENT_ROOT]."/lib/log/".date("Ymd").".log";
		$fp = fopen($fname,"a+");
		$script = date("Y-m-d H:i:s")."\t".$_SERVER[REMOTE_ADDR]."\t".$_SERVER[REQUEST_URI]."\t$script\n";

		fwrite($fp,$script);
		fclose($fp);
	}

	function sqlQuery($sql,$isImmediate=false)	{

		if($sql != "commit" && $sql != "rollback") {
			$this->lastQuery = $sql;
		}

		$result = @mysql_query($sql,$this->dbConnection);
		if($isImmediate)
			@mysql_query("commit",$this->dbConnection);

		if($result === false)
		{
			$this->errno = mysql_errno();
			$this->err_msg = mysql_error()."\n$sql";
			//echo iconv("euckr","utf8",$this->err_msg)."<br>";
			$this->writeLog("FAIL ::\t$this->err_msg\t::\t".$sql);
			return false;
		}

		$this->writeLog("SUCCESS\t".$sql);

		return $result;
	}

	function sqlFetchQuery($sql)	{
		$result = $this->sqlQuery($sql);
		return $this->sqlFetch($result);
	}

	function getRecordsFromQuery($sql)	{
		$result = $this->sqlQuery($sql);
		if($result === false)
		{
			$this->errno = mysql_errno();
			$this->err_msg = mysql_error();
			return false;
		}

		while($data = $this->sqlFetch($result))
		{
			$result_datas[] = $data;
		}
		return $result_datas;
	}

	function getRecord($table,$condition,$field="")	{
		$sql = "select * from $table where $condition";
		$result = $this->sqlQuery($sql);

		$data = $this->sqlFetch($result);

		if($field=="")
			return $data;
		else
			return $data[$field];
	}

	function getRecords($table,$condition="")	{
		if($condition=="")
			return $this->getRecordsFromQuery("select * from $table");
		else
			return $this->getRecordsFromQuery("select * from $table where $condition");
	}

	function getRecords2($table,$condition="",$extra)	{
		if($condition=="")
			return $this->getRecordsFromQuery("select * from $table $extra");
		else
			return $this->getRecordsFromQuery("select * from $table where $condition $extra");
	}

	function getRecordSum($table,$fieldname,$condition="") {
		if($condition=="")
			$sql = "select sum($fieldname) fsum from $table";
		else
			$sql = "select sum($fieldname) fsum from $table where $condition";

		$data = $this->sqlFetchQuery($sql);

		return $data[fsum];

	}

	function sqlFetch($result)	{
		$data = @mysql_fetch_assoc($result);
		$this->errno = @mysql_errno($this->dbConnection);
		$this->err_msg = @mysql_error()."\n$sql";

		return $this->errno == 0 ? $data : false;
	}

	function sqlFetchRow($result)	{
		$data = @mysql_fetch_row($result);
		$this->errno = mysql_errno($this->dbConnection);

		return $this->errno == 0 ? $data : false;
	}

	function commit()	{
		$this->sqlQuery("commit");
	}

	function rollback()	{
		$this->sqlQuery("rollback");
	}

	function begin()	{
		$this->sqlQuery("start transaction");
	}

	function insertTable($table,$data,$isImmediate=false)	{
		$data = $this->validateFields($table,$data);

		foreach($data as $key => $value)
		{
			$keys[] = addslashes($key);
			$datas[] = addslashes($value);
		}

		$keys = implode(",",array_values($keys));
		$datas = "'".implode("','",array_values($datas))."'";

		$sql = "insert into $table ($keys) values ($datas)";

		if($isImmediate)
		{
			$this->begin();
			$result = $this->sqlQuery($sql);
			$this->lastInsertId = mysql_insert_id();

			if($result === false)
			{
				$this->rollback();
			}
			else
			{
				$this->commit();
				$result = true;
			}

			return $result;
		}
		else
		{
			$r = $this->sqlQuery($sql);
			$this->lastInsertId = mysql_insert_id();

			return $r;
		}
	}

	function updateTable($table,$data,$condition,$isImmediate=false)	{
		$data = $this->validateFields($table,$data);

		foreach($data as $key => $value)
		{
			$datas[] = $key."='".$value."'";
		}
		$datas = @implode(",",$datas);

		$sql = "update $table set $datas where $condition";

		if($isImmediate)
		{
			$this->begin();
			$result = $this->sqlQuery($sql);

			if($result === false)
			{
				$this->rollback();
				$result = false;
			}
			else
			{
				$this->commit();
				$result = true;
			}

			return $result;
		}
		else
		{
			return $this->sqlQuery($sql);
		}
	}

	function deleteTable($table,$condition,$isImmediate=false) {
		$sql = "delete from $table where $condition";

		if($isImmediate)
		{
			$this->begin();
			$result = $this->sqlQuery($sql);

			if($result === false)
			{
				$this->rollback();
				$result = false;
			}
			else
			{
				$this->commit();
				$result = true;
			}
			return $result;
		}
		else
		{
			return $this->sqlQuery($sql);
		}
	}

	function getError()	{
		$rtn[errno] = $this->errno;
		$rtn[msg] = $this->err_msg;

		return $rtn;
	}

	function getErrorNo()	{
		return $this->errno;
	}

	function getErrorMessage()	{
		return $this->err_msg;
	}

	function getDataCount($table,$condition="")	{
		if($condition=="")
			$sql = "select count(*) from $table";
		else
		{
			$sql = "select count(*) from $table where $condition";
		}
		$result = $this->sqlQuery($sql);

		$cnt = $this->sqlFetchRow($result);
		return $cnt[0];
	}

	function getConnection() {
		return $this->dbConnection;
	}

	function validateFields($table,$data,$isclear=true)	{
		$result = $this->sqlQuery("desc $table");

		while($fd = $this->sqlFetch($result))
		{
			$fields[] = $fd[Field];
		}

		$keys = array_keys($data);
		foreach($keys as $key)
		{
			@reset($fields);
			if(!@in_array($key,$fields))
				if($isclear)
					unset($data[$key]);
				else
					return false;
		}

		return $data;
	}
}


/*
 Data Manipulation Common Class
*/

class IDCCommon extends DB {

	protected $dataTable;
	protected $searchKeyField;
	protected $keyValue;
	protected $infoLoaded = false;

	public $processError;
	public $data;

	/*
	$info[table]
	$info[searchKey]
	$info[keyValue]
	*/
	function __construct($info)	{
		parent::__construct();

		$kf = $info[searchKey]; // set default search key
		$value = $info[keyValue];

		$this->init($info[table],$kf);

		if($value != "") {
			$this->setInfo($value, $kf);
		}
	}

	// 초기화
	function init($dataTable, $keyfield)	{
		$this->dataTable = $dataTable;
		$this->searchKeyField = $keyfield;
	}

	// 현재 정보 취득
	function setInfo($value, $keyfield="") {

		$keyfield = $keyfield=="" ? $this->searchKeyField : $keyfield;
		$this->keyValue = $value;

		if($keyfield == "") return false;

		$this->data = $this->sqlFetchQuery("select * from $this->dataTable where $keyfield='$value'");

		$this->infoLoaded = is_array($this->data) && $this->data[$keyfield] == $value;

		return $this->infoLoaded;
	}

	function checkRequired($fieldInfo, $data) {

		foreach($data as $key => $value) {
			if(isset($fieldInfo[$key]) && $value == "") {
				$this->processError = $fieldInfo[$key]." 누락";

				return false;
			}
		}

		return true;
	}

	function getInfo() {

		if(!$this->infoLoaded) return false;

		return $this->data;
	}

	// 정보 수정
	function commonModify($updateCondition, $modifyData="") {

//		if(!$this->infoLoaded) return false;

		$update_data = is_array($modifyData) ? $modifyData: $this->data;

		if(!is_array($update_data)) return false;

		return $this->updateTable($this->dataTable,$update_data,$updateCondition,true);
	}

	/*	수정	*/
	function data_modify($updateCondition="", $info = "") {

		if($updateCondition == "" && $info == "" && !$this->infoLoaded) return false;

		if($updateCondition == "") {
			$kf = $this->searchKeyField;
			$kv = $this->keyValue;
			$updateCondition = "$kf='$kv'";
		}

		$update_data = is_array($info) ? $info: $this->data;

		return $this->commonModify($updateCondition,$update_data);
	}

	function commonRegister($regData, $infoLoad=true) {

		$r = $this->insertTable($this->dataTable,$regData,true);


		if(!$r) return false;

		if($infoLoad) $this->setInfo($regData[$this->searchKeyField], $this->searchKeyField);

		return true;
	}

	/*	등록	*/
	function data_register($reg_data) {
		return $this->commonRegister($reg_data);
	}

	/*	삭제	*/
	function data_delete($deleteCondition="") {

		if($deleteCondition == "" && $this->infoLoaded) {

			$keyField = $this->searchKeyField;
			$keyValue = $this->data[$keyField];

			$this->deleteTable($this->dataTable,"{$keyField}='{$keyValue}'",true);

		}
		else {
			$this->deleteTable($this->dataTable,$deleteCondition,true);
		}
	}

	function initError() {
		$this->processError = "";
	}
}

class CMonServer extends DB {

	public $processError;


	function __construct()	{

		$host = "221.141.1.163";
		$dbname = "monitoring2";
		$dbid = "monitoring2";
		$dbpw = "maru@@";

//		parent::__construct($host,$dbname,$dbid,$dbpw);
		parent::__construct();

	}

	function checkRequired($fieldInfo, $data) {

		foreach($data as $key => $value) {
			if(isset($fieldInfo[$key]) && $value == "") {
				$this->processError = $fieldInfo[$key]." 누락";

				return false;
			}
		}

		return true;
	}

	function getInternationalInfo() {
		$sql = "select * from mi_country";

		$datas = $this->getRecordsFromQuery($sql);

		return $datas;
	}

	function getIdcInfo($idc_idx="") {

		if($idc_idx != "") $cond[] = "idc_idx='$idc_idx'";

		if(isset($cond)) {
			$conds = " where ".implode(" and ",$cond);
		}

		$sql = "select * from mi_idc $conds";

		$datas = $this->getRecordsFromQuery($sql);

		return $datas;
	}

	function getIdcCompanyInfo($idc_no="") {

		if($idc_no != "") $cond[] = "idc_no='$idc_no'";

		if(isset($cond)) {
			$conds = " where ".implode(" and ",$cond);
		}

		$sql = "select * from idc_company_info $conds";

		$datas = $this->getRecordsFromQuery($sql);

		return $datas;
	}

	function getSwitchInfo($idc_no="", $s_type="") {

		if($idc_no != "") $cond[] = "idc_no='$idc_no'";
		if($s_type != "") $cond[] = "s_type='$s_type'";

		if(isset($cond)) {
			$conds = " where ".implode(" and ",$cond);
		}

		$sql = "select * from switch_info $conds";

		$datas = $this->getRecordsFromQuery($sql);

		return $datas;
	}

	function getPortInfo() {

		$cond[] = "s_no='$s_no'";

		if(isset($cond)) {
			$conds = " where ".implode(" and ",$cond);
		}

		$sql = "select * from port_info $conds";

		$datas = $this->getRecordsFromQuery($sql);

		return $datas;
	}




}

class CEmployee extends DB {

	var $data;
	var $infoLoaded = false;

	function __construct()	{
		parent::__construct();
	}

	function checkEmployee($userid, $password) {
		$userid = addslashes(trim($userid));
		$password = addslashes(trim($password));

		if($userid == "") return -1; // 아이디 공백
		if($password == "") return -4;

		$sql = "select * from mi_admin_employee where userid='$userid'";
		$this->data = $this->sqlFetchQuery($sql);
		$this->infoLoaded = is_array($this->data);

		if(!$this->infoLoaded) {
			return -2; // 아이디 없음
		}

		if($this->data[passwd] == md5($password)) return 0; // 체크성공
		else return -3; // 비밀번호 틀림
	}

	function login($userid, $password) {
		$userid = trim($userid);
		$password = trim($password);

		$result = $this->checkEmployee($userid, $password);

		if($result == 0) {

			$this->updateLoginTime();

			$_SESSION['LOGIN_NAME'] = $this->data[emp_name];
			$_SESSION['PART'] =      $this->data[part];
			$_SESSION['LEVEL'] =      $this->data[level];
			$_SESSION['LOGIN_IDX'] =  $this->data[emp_idx];
			$_SESSION['LOGIN_ID'] =  $userid;

      return true;
		}
		else
      return $result;
	}

	function updateLoginTime() {
		if(!$this->infoLoaded) return false;

		$lt = date("Y-m-d H:i:s");
		$emp_idx = $this->data[emp_idx];
		$this->sqlQuery("update mi_admin_employee set lastlogin='$lt' where emp_idx='$emp_idx'");
		$this->commit();

		return true;
	}
}

/*
발주데이터 클래스

발주관련 모든 데이터 처리 클래스
*/
class COrder extends IDCCommon {

	function __construct() {
		parent::__construct();
	}

	function register() {
	}

	function modify() {
	}

	function delete_data() {
	}
}

class CCommonFirewallPolicy extends IDCCommon {

	function __construct($value="",$kf="")	{

		$kf = $kf == "" ? "cfp_idx" : $kf; // set default search key

		$info[table] = "mi_cfp_info";
		$info[searchKey] = $kf;
		$info[keyValue] = $value;

		parent::__construct($info);
	}

	// 등록
	function register($reg_data) {
		$reg_data[regdate] = $reg_data[regdate] == "" ? date("Y-m-d") : $reg_data[regdate];
		$reg_data[pol_status] = $reg_data[pol_status] == "" ? 2 : $reg_data[pol_status];
		$reg_data[emp_idx] = $reg_data[emp_idx] == "" ? $_SESSION[LOGIN_IDX] : $reg_data[emp_idx];

		$result = $this->commonRegister($reg_data);

		if($result) {
			$cfp_idx = $this->lastInsertId;

			$server_datas = $this->getRecordsFromQuery("select * from mi_server where server_status=1 and use_cfp=1 order by sr_idx asc");

			// pfp 데이터 생성
			foreach($server_datas as $idx => $server_data) {
				unset($pfp_data);
				$pfp_data = $reg_data;

				$pfp_data[cfp_idx] = $cfp_idx;
				$pfp_data[mb_idx] = $server_data[mb_idx];
				$pfp_data[scode] = $server_data[scode];
				$pfp_data[pol_ststus] = 2;
				$pfp_data[server_ip] = $server_data[server_ip];

				$this->insertTable("mi_server_cfp",$pfp_data,true);
			}
		}

		return $result;
	}

	// 수정
	function modify($cfp_idx,$data) {

		$data[pol_status] = 7;
		$result =  $this->data_modify("cfp_idx='$cfp_idx'",$data);

		if($result) {
			$result = $this->updateTable("mi_server_cfp",$data,"cfp_idx='$cfp_idx'",true);
		}

		return $result;
	}

	function data_delete_wait($cfp_idx) {
		$table = $this->dataTable;

		$org_data = $this->getRecord($table,"cfp_idx='$cfp_idx'");

		$up_data[pol_status] = 6;
		$up_data[emp_idx] = $_SESSION[LOGIN_IDX];

		$this->updateTable($table,$up_data,"cfp_idx='$cfp_idx'",true);

		$this->updateTable("mi_pfp_info",$up_data,"cfp_idx='$cfp_idx'",true);
	}

	function change_status($cfp_idxs, $pol_status) {
		$data[pol_status] = $pol_status;

		$cfp_idxs = implode(",",$cfp_idxs);
		$result =  $this->data_modify("cfp_idx in ($cfp_idxs)",$data);

		if($result) {
			$result = $this->updateTable("mi_server_cfp",$data,"cfp_idx in ($cfp_idxs)",true);
		}

		return $result;
	}

	function get_cfp_idxs() {

		$sql = "select cfp_idx from mi_cfp_info where pol_status in (1,2,7)";

		$datas = $this->getRecordsFromQuery("select * from mi_server where server_status=1 and use_cfp=1 order by sr_idx asc");

		foreach($datas as $idx => $data) {
			$rtn_data[] = $data[cfp_idx];
		}

		return $rtn_data;
	}

	function cfp_firewall_apply($scode) {
	  // 지정된 서버의 방화벽 정책을 적용한다

	  /*
	    pol_status 에 따른 처리 방법

			차단(1)
	    	차단(1) : 차단적용
	    	차단대기(2) : 차단적용 -> 데이터는 차단으로 변경

	    삭제(5)
				대상데이터는 삭제표시. 나머지 데이터를 이용해 차단데이터 조립후 API호출

	    실제 API 전송은 차단 데이터만 전송함 (서버측에서 정책을 무조건 덮어쓰는 방식이므로 이전에 차단등록 되어있는 것도 모두 전송해야함).

	    차단데이터 없으면 별도의 API호출
	  */

		// 해당서버 상태 조사

		// cfp 미사용이면 cfp 미사용 API 호출

		// cfp 사용이면

		// cfp정책리스트 추출 :: 차단, 차단대기, 수정 상태의 데이터
		$cfp_idxs = $this->get_cfp_idxs(); // 차단, 차단대기, 수정 상태의 데이터

		// cfp정책 조합

		// api 호출

		return true;
	}

	function update_cfp_status() {
		$sql = "update mi_cfp_info set pol_status = 1 where pol_status in (2,7)";
		$this->sqlQuery($sql);

		$sql = "update mi_cfp_info set pol_status = 3 where pol_status in (4)";
		$this->sqlQuery($sql);

		$sql = "update mi_cfp_info set pol_status = 5 where pol_status in (6)";
		$this->sqlQuery($sql);

		$this->commit();

	}

	function update_use_cfp($use_cfp, $sr_idx) {

		$use_cfp = $use_cfp == 1 ? 2 : 1;
		$sql = "update mi_server set use_cfp = '$use_cfp' where sr_idx='$sr_idx'";
		$this->sqlQuery($sql);

		$scode = $this->getRecord("mi_server","sr_idx='$sr_idx'","scode");

		$cfp_idxs = $this->get_cfp_idxs();

		$server_data = $this->sqlFetchQuery("select * from mi_server where sr_idx='$sr_idx'");

		if($use_cfp == 1) {
			// 미사용 -> 사용

			// cfp정책 복사

			$sql = "select * from mi_cfp_info order by cfp_idx asc";
			$cfp_datas = $this->getRecordsFromQuery($sql);

			// pfp 데이터 생성
			foreach($cfp_datas as $idx => $cfp_data) {
				unset($pfp_data);
				$pfp_data = $cfp_data;

				$pfp_data[cfp_idx] = $cfp_idx;
				$pfp_data[mb_idx] = $server_data[mb_idx];
				$pfp_data[scode] = $scode;
				$pfp_data[pol_ststus] = 2;
				$pfp_data[server_ip] = $server_data[server_ip];

				$this->insertTable("mi_server_cfp",$pfp_data,true);
			}

			// api적용
			$this->cfp_firewall_apply($scode);
		}
		else if($use_cfp == 2) {
			// 사용 -> 미사용

			// cfp정책 제거
			$this->sqlQuery("delete from mi_server_cfp where scode='$scode'");
			// api적용 :: 해당서버의 모든 정책 제거
			$this->cfp_firewall_apply($scode);
		}

		$this->commit();
	}

}

/*
$m = new CMember("power0k_1");
var_dump($m);
*/

//$tt = get_defined_functions();

//var_dump($tt[user]);
?>